import os
import shutil
import sys

param = {}


def read_file_to_dict():
    # 读取文件，将文件内容插入字典
    file = open('../group_vars/all.yml')
    content = file.readlines()

    for line in content:
        line_str = line.strip()
        if len(line_str) != 0:
            split_line = line_str.split(':')
            param[split_line[0]] = split_line[1].strip()


def check_file_exist():
    # 查找文件包是否存在，如果文件都存在则copy到指定位置
    pkgnm = ['PKG_HARBOR', 'PKG_K8S_NODE', 'PKG_CRI_DOKER', 'PKG_ETCD', 'PKG_K8S_SERVER', 'PKG_HELM', 'PKG_CFSSL']
    flag_ = 0
    for nm in pkgnm:
        if not os.path.exists(param[nm]):
            print(param[nm])
            flag_ = 1

    if flag_:
        print("file no exist")
        return 1
    return 0


def copy_file():
    print("copy file")
    shutil.copyfile(param['PKG_K8S_NODE'], '../inst-k8s-node/files/' + param['PKG_K8S_NODE'])
    shutil.copyfile(param['PKG_HARBOR'], '../inst-docker-ce/files/' + param['PKG_HARBOR'])
    shutil.copyfile(param['PKG_CRI_DOKER'], '../inst-docker-ce/files/' + param['PKG_CRI_DOKER'])
    shutil.copyfile(param['PKG_ETCD'], '../inst-etcd/files/' + param['PKG_ETCD'])
    shutil.copyfile(param['PKG_K8S_SERVER'], '../inst-k8s-master/files/' + param['PKG_K8S_SERVER'])
    shutil.copyfile(param['PKG_HELM'], '../inst-k8s-master/files/' + param['PKG_HELM'])
    shutil.copyfile(param['PKG_CFSSL'], '../create_ca/files/' + param['PKG_CFSSL'])


def remove_file(filenm):
    if os.path.exists(filenm):
        os.remove(filenm)

def delete_file():
    print("delete file")
    filenm = '../inst-k8s-node/files/' + param['PKG_K8S_NODE']
    remove_file(filenm)

    filenm = '../inst-docker-ce/files/' + param['PKG_HARBOR']
    remove_file(filenm)

    filenm = '../inst-docker-ce/files/' + param['PKG_CRI_DOKER']
    remove_file(filenm)

    filenm = '../inst-etcd/files/' + param['PKG_ETCD']
    remove_file(filenm)
    
    filenm = '../inst-k8s-master/files/' + param['PKG_K8S_SERVER']
    remove_file(filenm)

    filenm = '../inst-k8s-master/files/' + param['PKG_HELM']
    remove_file(filenm)
    
    filenm = '../create_ca/files/' + param['PKG_CFSSL']
    remove_file(filenm)

if __name__ == '__main__':
    try:
        flag = sys.argv[1]
        if flag == 'copy':
            read_file_to_dict()
            if check_file_exist():
                print("file no exist")
                exit(1)
            copy_file()
        if flag == 'delete':
            read_file_to_dict()
            delete_file()
    except Exception as e:
        print(sys.argv)
        print(e)
